<?php

/**
 * Created by PhpStorm.
 * User: dumbledore
 * Date: 2018/2/26
 * Time: 下午2:37
 */
class Order extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->library('form_validation');//加载表单验证类库
        $this->load->helper('json');
        $this->load->helper('common');
        $this->load->model('user_model');
        $this->load->model('member_model');
        $this->load->model('order_model');
        $this->load->model('cart_model');
        $this->load->model('api_model');
        $this->load->model('goods_model');
        $this->load->model('customer_model');
        $this->load->library('session');
    }

    //普通订单列表
    public function approve_order()
    {
        $customer_id = $this->session->customer_id;
        $identity = $this->session->customer_info['identity'];
        $where = "";
        if (isset($_GET['id']) && $_GET['id'] == 6) {
            $id = $_GET['id'];
            $where = $where . " AND (status = 2 OR status = 4)";
        } elseif (isset($_GET['id']) && $_GET['id'] == 7) {
            $id = $_GET['id'];
            $where = $where . " AND (status = 3 OR status = 5)";
        } elseif (isset($_GET['id']) && $_GET['id'] == 1) {
            $id = $_GET['id'];
            $where = $where . " AND status = 1";
        } else {
            $id = "";
        }
        if (isset($_GET['order_bn']) && $_GET['order_bn'] != '') {
            $order_bn = $_GET['order_bn'];
            $order = $this->db->where(array('order_bn' => $order_bn))->from('app_order')->get()->row_array();
            if ($order) {
                $where = $where . " AND shop_order_id =" . $order['shop_order_id'];
            } else {
                $where = $where . " AND shop_order_id ='" . $order_bn . "'";
            }

        } else {
            $order_bn = '';
        }

        $listRows = 10;//每页数量
        $sql = "select id from  app_temp  where customer_id ='" . $customer_id . "' " . $where . " order by id desc";

        $count = count($this->db->query($sql)->result_array());
        $num = $count / $listRows;

        if (floor($num) == $num) {
            $num = floor($num);
        } else {
            $num = floor($num) + 1;
        }

        if (isset($_GET['p'])) {
            $p = $_GET['p'];
        } else {
            $p = 1;
        }
        if ($p < $num) {
            $data['nexturl'] = base_url() . 'order/approve_order?p=' . ($p + 1) . '&id=' . $id;
        } else {
            $data['nexturl'] = 'javascript:;';
        }
        if ($p > 1) {
            $data['preurl'] = base_url() . 'order/approve_order?p=' . ($p - 1) . '&id=' . $id;
        } else {
            $data['preurl'] = 'javascript:;';
        }

        $firstRow = $listRows * ($p - 1);

        $sql = "select  *,(select status from app_order where app_order.shop_order_id = app_temp.shop_order_id) as shop_status,(select order_bn from app_order where app_order.shop_order_id = app_temp.shop_order_id) as shop_order_bn from  app_temp  where customer_id ='" . $customer_id . "' " . $where . " order by id desc limit " . $firstRow . "," . $listRows . "";

        $data['list'] = $this->db->query($sql)->result_array();
        foreach ($data['list'] as $key => $value) {
            $data['list'][$key]['detail'] = json_decode($value['detail'], true);
            $sql = "select  reason,created_at,updated_at,verify_status,identity  from  app_temp_approval  where temp_id ='" . $value['id'] . "'";
            $data['list'][$key]['temp_approval'] = $this->db->query($sql)->result_array();
        }
        //审核通过的个数
        $sql = "select  id from  app_temp  where customer_id ='" . $customer_id . "' AND status = 1";
        $data['count_tongguo'] = count($this->db->query($sql)->result_array());
        //审核中的个数
        $sql = "select  id from  app_temp  where customer_id ='" . $customer_id . "' AND (status = 2 OR status = 4)";
        $data['count_zhong'] = count($this->db->query($sql)->result_array());
        //审核未通过的个数
        $sql = "select  id from  app_temp  where customer_id ='" . $customer_id . "' AND (status = 3 OR status = 5)";
        $data['count_weitongguo'] = count($this->db->query($sql)->result_array());
        $data['id'] = $id;
        $data['p'] = $p;
        $data['num'] = $num;
        $data['order_bn'] = $order_bn;
        $this->load->view('order/approve_order', $data);

    }

    //普通订单列表
    public function common_order()
    {
        $customer_id = $this->session->customer_id;
        $identity = $this->session->customer_info['identity'];
        $where = "";
        if (isset($_GET['id']) && $_GET['id'] != '') {
            $id = $_GET['id'];
            $where = $where . " AND status =" . $id;
        } else {
            $id = "";
        }

        if (isset($_GET['order_bn']) && $_GET['order_bn'] != '') {
            $order_bn = $_GET['order_bn'];
            $where = $where . " AND order_bn ='" . $order_bn . "'";
        } else {
            $order_bn = '';
        }

        $listRows = 10;//每页数量
        $sql = "select id from  app_order  where customer_id ='" . $customer_id . "' " . $where . " order by id desc";

        $count = count($this->db->query($sql)->result_array());
        $num = $count / $listRows;

        if (floor($num) == $num) {
            $num = floor($num);
        } else {
            $num = floor($num) + 1;
        }

        if (isset($_GET['p'])) {
            $p = $_GET['p'];
        } else {
            $p = 1;
        }
        if ($p < $num) {
            $data['nexturl'] = base_url() . 'order/common_order?p=' . ($p + 1) . '&id=' . $id;
        } else {
            $data['nexturl'] = 'javascript:;';
        }
        if ($p > 1) {
            $data['preurl'] = base_url() . 'order/common_order?p=' . ($p - 1) . '&id=' . $id;
        } else {
            $data['preurl'] = 'javascript:;';
        }

        $firstRow = $listRows * ($p - 1);

        $sql = "select  *  from  app_order  where customer_id ='" . $customer_id . "' " . $where . " order by id desc limit " . $firstRow . "," . $listRows . "";
        $data['list'] = $this->db->query($sql)->result_array();
        foreach ($data['list'] as $key => $value) {
            $data['list'][$key]['detail'] = json_decode($value['detail'], true);
        }

        $sql = "select  id from  app_order  where customer_id ='" . $customer_id . "' AND status = 4";
        $data['count_daifukuan'] = count($this->db->query($sql)->result_array());
        $sql = "select  id from  app_order  where customer_id ='" . $customer_id . "' AND status = 3";
        $data['count_daiqueren'] = count($this->db->query($sql)->result_array());
        $data['id'] = $id;
        $data['p'] = $p;
        $data['num'] = $num;
        $data['order_bn'] = $order_bn;
//        echo '<pre>';
//        var_dump($data['list']);
//        echo '</pre>';
        $this->load->view('order/common_order', $data);

    }

    //修改订单
    public function modify()
    {
        $post = $this->input->post();
        $id = $post['id'];
        if (isset($post['type']) && $post['type'] == 1) {
            $sql = "select customer_id,detail from  app_order  where id =" . $id;
        } else {
            $sql = "select customer_id,detail from  app_temp  where id =" . $id;
        }
        $result = $this->db->query($sql)->row_array();
        $row = json_decode($result['detail'], true);
        $flag = 1;
        foreach ($row['products'] as $good) {
            $product_id = $good['product_id'];
            $num = $good['count'];
            $res = $this->cart_model->add_cart($result['customer_id'], $product_id, $num);
            if (!$res) {
                $flag = 0;
            }
        }
        if ($flag) {
            send_json(array('code' => 0, 'data' => '', 'msg' => ''));
        } else {
            send_json(array('code' => 1, 'data' => '', 'msg' => "操作失败"));
        }
    }

    //订单详情，审批订单
    public function approve()
    {
        $customer_id = $this->session->customer_id;
        $identity = $this->session->customer_info['identity'];
        $arr_user = $this->customer_model->get_admin_customer($customer_id,1);
        if (!$arr_user) {
            exit('操作失败');
        }

        if (isset($_GET['id']) && $_GET['id'] != "") {
            $id = $_GET['id'];
        } else {
            exit('需要审批的订单不存在');
        }
        $field = 'id,customer_id,money,address_id,invoice_id,shop_order_id,detail,status,reason,remark,update_at,express_fee,created_at,content,
                (SELECT name FROM app_address WHERE app_address.id=app_temp.address_id) AS address_name,
                (SELECT province FROM app_address WHERE app_address.id=app_temp.address_id) AS address_province,
                (SELECT city FROM app_address WHERE app_address.id=app_temp.address_id) AS address_city,
                (SELECT district FROM app_address WHERE app_address.id=app_temp.address_id) AS address_district,
                (SELECT postcode FROM app_address WHERE app_address.id=app_temp.address_id) AS address_postcode,
                (SELECT phone FROM app_address WHERE app_address.id=app_temp.address_id) AS address_phone,
                (SELECT address FROM app_address WHERE app_address.id=app_temp.address_id) AS address_address,
                (SELECT status FROM app_order WHERE app_order.shop_order_id=app_temp.shop_order_id) AS shop_status,
                (SELECT invoice_company_name FROM app_invoice WHERE app_invoice.id=app_temp.invoice_id) AS invoice_company_name,
                (SELECT invoice_tel FROM app_invoice WHERE app_invoice.id=app_temp.invoice_id) AS invoice_tel,
                (SELECT invoice_code FROM app_invoice WHERE app_invoice.id=app_temp.invoice_id) AS invoice_code,
                (SELECT invoice_bank FROM app_invoice WHERE app_invoice.id=app_temp.invoice_id) AS invoice_bank,
                (SELECT invoice_account FROM app_invoice WHERE app_invoice.id=app_temp.invoice_id) AS invoice_account,
                (SELECT invoice_address FROM app_invoice WHERE app_invoice.id=app_temp.invoice_id) AS invoice_address,
                (SELECT invoice_type FROM app_invoice WHERE app_invoice.id=app_temp.invoice_id) AS invoice_type';
        $data['result'] = $this->db->select($field)->get_where('app_temp', array('id' => $id, 'customer_id' => $customer_id))->row_array();

        $data['detail'] = json_decode($data['result']['detail'], true);

        if (!$data['result']) {
            exit('需要审批的订单不存在');
        }


        if($identity == 2){
            $parent_info = $this->customer_model->get_parent_info($customer_id);
            $data['parent_name'] = $parent_info['username'];
            $data['parent_email'] = $parent_info['email'];
            $data['parent_id'] = $parent_info['id'];
            $where = array('temp_id' => $data['result']['id'], 'identity' => 1);
            $res = $this->db->select("id,verify_status,remark,reason")->where($where)->get('app_temp_approval')->row_array();

            if ($res) {
                $data['remark'] = $res['remark'];
                $data['reason'] = $res['reason'];
            } else {
                $data['remark'] = "";
                $data['reason'] = "";
            }

        }
        if($identity == 3){
            $parent_info = $this->customer_model->get_parent_info($customer_id);
            if($parent_info['status'] == 0){
                if ($data['result']['status'] == 0) {
                    $data['parent_name'] = "";
                } elseif ($data['result']['status'] == 4 || $data['result']['status'] == 5) {
                    $where = array('temp_id' => $data['result']['id'], 'identity' => 1);
                    
                    if(count($arr_user) == 2){
                        $data['parent_name'] = $arr_user[1]['username'];
                        $data['parent_email'] = $arr_user[1]['email'];
                        $data['parent_id'] = $arr_user[1]['id'];
                    }else{
                        $data['parent_name'] = $arr_user[0]['username'];
                        $data['parent_email'] = $arr_user[0]['email'];
                        $data['parent_id'] = $arr_user[0]['id'];
                    }
                } else {
                    $where = array('temp_id' => $data['result']['id']);
                    if(count($arr_user) == 2){
                        $data['parent_name'] = $arr_user[1]['username'];
                    }else{
                        $data['parent_name'] = $arr_user[0]['username'];
                    }
                }
                $res = $this->db->select("id,verify_status,remark,reason")->where($where)->order_by("id", "desc")->get('app_temp_approval')->row_array();
                if ($res) {
                    $data['remark'] = $res['remark'];
                    $data['reason'] = $res['reason'];
                } else {
                    $data['remark'] = "";
                    $data['reason'] = "";
                }  
            }else{
                if ($data['result']['status'] == 0) {
                    $data['parent_name'] = "";
                } elseif ($data['result']['status'] == 2 || $data['result']['status'] == 3) {
                    $where = array('temp_id' => $data['result']['id'], 'identity' => 2);
                    $data['parent_name'] = $arr_user[0]['username'];
                    $data['parent_email'] = $arr_user[0]['email'];
                    $data['parent_id'] = $arr_user[0]['id'];
                } elseif ($data['result']['status'] == 4 || $data['result']['status'] == 5) {
                    $where = array('temp_id' => $data['result']['id'], 'identity' => 1);

                    if(count($arr_user) == 2){
                        $data['parent_name'] = $arr_user[1]['username'];
                        $data['parent_email'] = $arr_user[1]['email'];
                        $data['parent_id'] = $arr_user[1]['id'];
                    }else{
                        $data['parent_name'] = $arr_user[0]['username'];
                        $data['parent_email'] = $arr_user[0]['email'];
                        $data['parent_id'] = $arr_user[0]['id'];
                    }
                } else {
                    $where = array('temp_id' => $data['result']['id']);
                    $res = $this->db->select("id")->where($where)->get('app_temp_approval')->result_array();
                    if (count($res) == 1) {
                        $data['parent_name'] = $arr_user[0]['username'];
                    } else {
                        if(count($arr_user) == 2){
                            $data['parent_name'] = $arr_user[1]['username'];
                        }else{
                            $data['parent_name'] = $arr_user[0]['username'];
                        }
                    }
                }

                $res = $this->db->select("id,verify_status,remark,reason")->where($where)->order_by("id", "desc")->get('app_temp_approval')->result_array();
                if ($res) {
                    $data['remark'] = $res[0]['remark'];
                    $data['reason'] = $res[0]['reason'];
                } else {
                    $data['remark'] = "";
                    $data['reason'] = "";
                }
            }
        }

        $where = array('temp_id' => $_GET['id']);
        $data['temp_reason'] = "";
        $data['out_single'] = $this->db->select("out_single_product_ids")->where($where)->get('app_temp_single_budget')->row_array();
        if ($data['out_single']) {
            $out_single_ids = "";
            foreach (unserialize($data['out_single']['out_single_product_ids']) as $key => $value) {
                $out_single_ids .= ',' . $key;
            }
            $out_single_ids_str = mb_substr($out_single_ids, 1, strlen($out_single_ids));
            $admin_shop_user_id = $this->user_model->customer_id_to_admin_to_shop_user_id($customer_id);
            $data['out_single_goods'] = $this->goods_model->company_goods_infoes($out_single_ids_str,$admin_shop_user_id);
            $data['temp_reason'] .= '单品超出预算,';
        }

        $data['out_month'] = $this->db->select("exceed_budget")->where($where)->get('app_temp_month_budget')->row_array();
        if ($data['out_month']) {
            $data['temp_reason'] .= '订单超出预算,';
        }

        $data['out_list'] = $this->db->select("out_list_product_ids")->where($where)->get('app_temp_out_list')->row_array();
        if ($data['out_list']) {
            $out_list_ids_str = unserialize($data['out_list']['out_list_product_ids']);
            $admin_shop_user_id = $this->user_model->customer_id_to_admin_to_shop_user_id($customer_id);
            $data['out_list_goods'] = $this->goods_model->company_goods_infoes($out_list_ids_str,$admin_shop_user_id);
            $data['temp_reason'] .= '商品超出选购范围,';
        }
        $data['temp_id'] = $_GET['id'];
        //等待时间
        $data['wait_time'] = wait_time($data['result']['created_at']);

        $this->load->view('order/approve', $data);
    }


    //订单详情 普通订单
    public function common()
    {
        $customer_id = $this->session->customer_id;
        $identity = $this->session->customer_info['identity'];

        if (!isset($_GET['id']) && !isset($_GET['shop_id'])) {
            exit('订单不存在');
        }

        if (isset($_GET['id']) && $_GET['id'] != "") {
            $id = $_GET['id'];
            $data['result'] = $this->db->get_where('app_order', array('id' => $id, 'customer_id' => $customer_id))->row_array();
            $where = array('temp_id' => $_GET['id']);
        } elseif (isset($_GET['shop_id']) && $_GET['shop_id'] != "") {
            $shop_id = $_GET['shop_id'];
            $data['result'] = $this->db->get_where('app_order', array('shop_order_id' => $shop_id, 'customer_id' => $customer_id))->row_array();
            $where = array('temp_id' => $_GET['shop_id']);
        } else {
            exit('订单不存在');
        }


        $data['detail'] = json_decode($data['result']['detail'], true);
        $data['address'] = json_decode($data['result']['address'], true);
        $data['invoice'] = json_decode($data['result']['invoice'], true);
        if (!$data['result']) {
            exit('订单不存在');
        }


        $data['temp_reason'] = "";
        $data['out_single'] = $this->db->select("out_single_product_ids")->where($where)->get('app_temp_single_budget')->row_array();
        if ($data['out_single']) {
            $out_single_ids = "";
            foreach (unserialize($data['out_single']['out_single_product_ids']) as $key => $value) {
                $out_single_ids .= ',' . $key;
            }
            $out_single_ids_str = mb_substr($out_single_ids, 1, strlen($out_single_ids));
            $admin_shop_user_id = $this->user_model->customer_id_to_admin_to_shop_user_id($customer_id);
            $data['out_single_goods'] = $this->goods_model->company_goods_infoes($out_single_ids_str,$admin_shop_user_id);
            $data['temp_reason'] .= '单品超出预算,';
        }

        $data['out_month'] = $this->db->select("exceed_budget")->where($where)->get('app_temp_month_budget')->row_array();
        if ($data['out_month']) {
            $data['temp_reason'] .= '订单超出预算,';
        }

        $data['out_list'] = $this->db->select("out_list_product_ids")->where($where)->get('app_temp_out_list')->row_array();
        if ($data['out_list']) {
            $out_list_ids_str = unserialize($data['out_list']['out_list_product_ids']);
            $admin_shop_user_id = $this->user_model->customer_id_to_admin_to_shop_user_id($customer_id);
            $data['out_list_goods'] = $this->goods_model->company_goods_infoes($out_list_ids_str,$admin_shop_user_id);
            $data['temp_reason'] .= '商品超出选购范围,';
        }
        //等待时间
        $data['wait_time'] = wait_time($data['result']['created_at']);

        $this->load->view('order/common', $data);
    }

    /*
    * 发送邮件至上级
    *
    */
    public function send_email_to_remind()
    {
        $post = $this->input->post();
        //邮箱验证
        if (!empty($post['email'])) {
            $row = $this->api_model->send_email_public($post['email'], '审批订单', $post['content']);
            if ($row !== false) {
                $this->db->where(array('id'=>$post['temp_id']))->update('app_temp',array('alert_time'=>time()));
                send_json(array('code' => 0, 'data' => '', 'msg' => "发送成功"));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => '发送失败'));
            }
        }else{
            send_json(array('code' => -1, 'data' => '', 'msg' => '上级邮箱不存在'));
        }

    }

    //取消订单
    public function quit_order()
    {
        $post = $this->input->post();

        $id = $post['id'];

        $data = array(
            'status' => 0,
            'update_at' => date('Y-m-d H:i:s',time())
        );
        $where = array('id' => $id);
        $bool = $customer = $this->db->where($where)->update('app_temp', $data);

        if ($bool) {
            send_json(array('code' => 0, 'data' => '', 'msg' => ''));
        } else {
            send_json(array('code' => 1, 'data' => '', 'msg' => "操作失败"));
        }
    }

//    public function autoJump2Url($time=3)
//    {
//
//        $str = <<<EOF
//<script>
//var oDiv = document.createElement('p');
//oDiv.setAttribute('id','time');
//document.getElementById('container').appendChild(oDiv);//动态生成p标签，container是CI框架这个404模板中自带的
//
//function vcodeTick(count) {
//    if (count < 0) {
//        return;
//    }
//    if(count == 0){
//        location.href ='index.php/cart/index';
//    }
//    document.getElementById('time').innerHTML=count + ' 秒后跳转';
//
//    count--;
//    setTimeout('vcodeTick(' + count + ')', 1000);
//}
//vcodeTick({$time});//执行方法
//</script>
//EOF;
//        return $str;
//    }

    //立即购买
    public function shop()
    {
        $post = $this->input->post();
        if (!$post) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        } else {
            if (!$this->session->customer_id) {
                send_json(array('code' => -2, 'data' => '', 'msg' => "请先重新登录"));
            } else {
                $product_id = $post['product_id'];
                $num = $post['count'];

                if ($product_id) {
                    $data = array(
                        'customer_id' => $this->session->customer_id,
                        'ids' => json_encode(array(array($product_id => $num))),
                        'type' => 0,
                        'time' => time()
                    );
                    $this->db->replace('app_temp_order', $data);
                } else {
                    send_json(array('code' => -1, 'data' => '', 'msg' => "请先选择商品"));
                }
            }
        }
    }

    //提交商品到购物车
    public function submit()
    {
        $customer_id = $this->session->customer_id;
        $post = $this->input->post();
        if (!$post) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        } else {
            if (!$this->session->customer_id) {
                send_json(array('code' => -2, 'data' => '', 'msg' => "请先重新登录"));
            } else {
                if ($post['ids']) {
                    $ids = array();
                    foreach (explode(',', $post['ids']) as $id) {
                        $where = array('id' => $id, 'customer_id' => $customer_id);
                        $goods = $this->db->where($where)->get('app_cart')->row_array();
                        if ($goods) {
                            $ids[] = array($goods['product_id'] => $goods['num']);
                        }
                    }
                    $data = array(
                        'customer_id' => $this->session->customer_id,
                        'ids' => json_encode($ids),
                        'type' => 1,
                        'time' => time()
                    );
                    $this->db->replace('app_temp_order', $data);
                } else {
                    send_json(array('code' => -1, 'data' => '', 'msg' => "请先选择商品"));
                }
            }
        }
    }

    //修改收货地址
    public function address()
    {
        $post = $this->input->post();
        if (!$post) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        } else {
            if (!$this->session->customer_id) {
                send_json(array('code' => -2, 'data' => '', 'msg' => "请先重新登录"));
            } else {
                if ($post['address_id']) {
                    $data = array(
                        'address_id' => $post['address_id']
                    );
                    $this->db->update('app_temp_order', $data, array('customer_id' => $this->session->customer_id));
                } else {
                    send_json(array('code' => -1, 'data' => '', 'msg' => "请先选择地址"));
                }
            }
        }
    }

    //提交订单页面
    public function detail()
    {
        $customer_id = $this->session->customer_id;
        $identity = $this->session->customer_info['identity'];

        $temp = $this->db->where('customer_id', $customer_id)->from('app_temp_order')->get()->row_array();


        //获取用户地址
        $where = array(
            'customer_id' => $customer_id
        );
        $data['address'] = $this->db->where($where)->get('app_address')->result_array();


        //获取商城用户id
        $shop_user_id = $this->user_model->customer_id_to_shop_user_id($customer_id);


        if (isset($temp['address_id']) && $temp['address_id']) {
            $where = array('id' => $temp['address_id']);
            if (strpos($temp['address_id'], '1_') !== false) {
                $data['zitiId'] = $temp['address_id'];
                $address['shop_id'] = $temp['address_id'];
                $data['addressId'] = "";
            } else {
                $data['addressId'] = $temp['address_id'];
                $data['zitiId'] = "";
                $address = $this->db->where($where)->select('shop_id')->get('app_address')->row_array();
            }

        } else {
            $where = array('customer_id' => $customer_id, 'is_default' => 1);
            $data['zitiId'] = "";
            $address = $this->db->where($where)->select('shop_id,id')->get('app_address')->row_array();
            $data['addressId'] = $address['id'];
        }


        //获取用户默认地址
//        if (isset($post['addressId'])) {
//            $where = array('id' => $post['addressId']);
//            if (strpos($post['addressId'], '1_') !== false) {
//                $data['zitiId'] = $post['addressId'];
//                $address['shop_id'] = $post['addressId'];
//                $data['addressId'] = "";
//            } else {
//                $data['addressId'] = $post['addressId'];
//                $data['zitiId'] = "";
//                $address = $this->db->where($where)->select('shop_id')->get('app_address')->row_array();
//            }
//
//        } else {
//            $where = array('customer_id' => $customer_id, 'is_default' => 1);
//            $data['zitiId'] = "";
//            $address = $this->db->where($where)->select('shop_id,id')->get('app_address')->row_array();
//            $data['addressId'] = $address['id'];
//        }


        $data['regionId'] = $address['shop_id'] ? $address['shop_id'] : 0;

        //请求商城判断商品是否在配送范围内接口
        $url = $this->config->item('shop_url') . "companymanagerapi/getPostageGoods/";
        $data_arr['time'] = time();
        $data_arr['key'] = md5($this->config->item('token_const_wjyh') . $data_arr['time']);
        $data_arr['buyer_id'] = $shop_user_id;
        $data_arr['address_id'] = $address['shop_id'] ? $address['shop_id'] : 0;

        $res = json_decode(curl_request($url, $data_arr), true);
        if ($res['code'] == 200) {
            $data['list'] = $res['data'];
        } else {
            exit($res['msg']);
        }

//        $ids = $this->input->post();


        if (!$temp || !$temp['ids']) {
            $this->session->set_flashdata('msg', '请重新下单!');
            redirect('cart/index');
            exit;
        }

        $ids['ids'] = $temp['ids'];

        $p = json_decode($temp['ids'], true);

        if (!count($p)) {
            exit('缺少参数,请重新选择商品');
        }

        $product_ids = '';
        foreach ($p as $k => $m) {
            foreach ($m as $id => $num) {
                $product_ids .= $id . ',';
            }
        }

        $data['goods'] = array();

        $admin_shop_user_id = $this->user_model->customer_id_to_admin_to_shop_user_id($customer_id);
        $goodsinfo = $this->goods_model->company_goods_infoes($product_ids,$admin_shop_user_id);
        if ($goodsinfo) {
            foreach ($goodsinfo as $key => $value) {
                foreach ($p as $k => $m) {
                    foreach ($m as $id => $num) {
                        if ($id == $value['goods_id']) {
                            $data['goods'][$key] = array('product_id' => $id, 'num' => $num);
                            $data['goods'][$key][] = $value;
                        }
                    }
                }
            }
        } else {
            $this->session->set_flashdata('msg', '系统错误!请稍后重新下单!');
            redirect('cart/index');
            exit;
        }

        $data['temp'] = $temp;

//        if (!count($ids)) {
//            exit('缺少参数,请重新选择商品');
//        }
//        $product_ids = '';
//        foreach (explode(",", $ids['ids']) as $id) {
//            $where = array('id' => $id, 'customer_id' => $customer_id);
//            $goods = $this->db->where($where)->get('app_cart')->row_array();
//            if (!$goods) {
//                exit('请选择商品');
//            }
//            $cart_goods[] = $goods;
//            $product_ids .= $goods['product_id'] . ',';
//        }
//        $data['goods'] = $this->goods_model->get_shop_goods_info_sync_cart($product_ids, $cart_goods);

        //获取U-M每月所剩的账期额度和admin总共所剩的账期额度
        $data['total_quota_left'] = $this->customer_model->member_total_quota_left_month($customer_id, $identity);
        if ($identity != 1) {
            $quota = $this->customer_model->u_m_single_quota($customer_id);
            $data['total_quota'] = $quota['total_quota'];

            //获取U-M单品商品额度
            $data['single_quota'] = $quota['single_quota'];

            //获取U-M用户清单id
            $data['list_id'] = $this->customer_model->u_m_list_goods_ids($customer_id);
            if(isset($data['list']['in_range_List']) && $data['list']['in_range_List'] != ""){
                foreach ($data['list']['in_range_List'] as $key => $value) {
                    if (($data['list_id'] && !in_array($value['goods_id'], $data['list_id'])) || ($data['single_quota'] < $value['price'] && $data['single_quota'] != 0)){
                        $data['approve_info']  = 1;
                    }
                }
            } 
        } else {
            $data['total_quota'] = "";
        }
        //获取自提地址.
        $url = $this->config->item("shop_url") . 'companymanagerapi/company_goods_packup/';
        $data_arr['time'] = time();
        $data_arr['key'] = md5($this->config->item("token_const_wjyh") . $data_arr['time']);
        $rs = curl_request($url, $data_arr);
        $result = json_decode($rs, true);

        if ($result['code'] == 200) {
            $data['ziti'] = $result['data'];
        } else {
            $data['ziti'] = "";
        }

        //获取admin的成本中心部门。
        if ($identity == 1) {
            $data['cost_center'] = $this->customer_model->get_admin_cost_center($customer_id);
        }
        if($identity == 2){
            $data['parent'] = $this->customer_model->get_parent_info($customer_id);
        }
        if($identity == 3){
            $parent_info = $this->customer_model->get_parent_info($customer_id);
            if($parent_info['status'] == 0){
                $data['parent'] = $this->customer_model->get_parent_info($parent_info['id']);
            }else{
                $data['parent'] = $this->customer_model->get_parent_info($customer_id);
            }
        }
        if($identity==1){
            $is_account = $this->db->where(array('customer_id'=>$customer_id))->select('is_account')->from('app_admin')->get()->row_array();
            $data['is_account'] = $is_account;
        }
        $data['ids'] = $ids['ids'];
        $data['identity'] = $identity;
        $data['customer_id'] = $customer_id;

        $this->load->view('order/detail', $data);
    }

    //创建订单
    public function create()
    {
        $customer_id = $this->session->customer_id;
        $identity = $this->session->customer_info['identity'];
        $where = array(
            'customer_id' => $customer_id
        );
        $post = $this->input->post();
        if (isset($post['bm'])) {
            $data['cost_center_id'] = $post['bm'];
        } else {
            $data['cost_center_id'] = $this->customer_model->query_customer_info($customer_id)['cost_center_id'];
        }
        //获取商城用户id
        $shop_user_id = $this->user_model->customer_id_to_shop_user_id($customer_id);
        
        $product_id_str = join(',', $post['recid']);
        $type = $post['submit_type'];

        if($type==1){
            //获取购物车商品
            $cart_goods = $this->db->where($where)->get('app_cart')->result_array();
        }else{
            $goods_info = $this->db->where(array('customer_id'=>$customer_id))->from('app_temp_order')->get()->row_array();
            $cart_goods = json_decode($goods_info['ids'],true);
        }
        $admin_shop_user_id = $this->user_model->customer_id_to_admin_to_shop_user_id($customer_id);

     
        $goods = $this->goods_model->get_shop_goods_info_sync_cart_type($product_id_str, $type,$cart_goods,$admin_shop_user_id);

        //获取U-M每月所剩的账期额度和admin总共所剩的账期额度
        $total_quota_left = $this->customer_model->member_total_quota_left_month($customer_id, $identity);
        if ($identity != 1) {
            $quota = $this->customer_model->u_m_single_quota($customer_id);
            //获取U-M单品商品额度
            $single_quota = $quota['single_quota'];
            $total_quota = $quota['total_quota'];
            //获取U-M用户清单id
            $list_id = $this->customer_model->u_m_list_goods_ids($customer_id);
            $money = 0;
            $goods_arr = [];
            $sku_info = [];
            $out_goods_arr = [];
            $goods_id_str = "";
            $cart_id = [];
            $out_money = 0;
          
            foreach ($goods as $k => $v) {
                foreach ($v[0]['goods_attr'] as $key => $value) {
                    $sku_info[$value['name']] = $value['value'];
                }
                if ($post['submit_type'] == 1) { 
                    //企业购物车id
                    $cart_id[$k] = $v['id'];
                }
                if($v[0]['adjust_price']){
                    $v[0]['goods_price'] = $v[0]['adjust_price'];
                }
                $money += $v[0]['goods_price'] * $v['num'];
                $goods_arr['products'][$k]['product_id'] = $v[0]['goods_id'];
                $goods_arr['products'][$k]['product_name'] = $v[0]['goods_name'];
                $goods_arr['products'][$k]['product_img'] = $v[0]['goods_main_img'];
                $goods_arr['products'][$k]['price'] = $v[0]['goods_cost_price'];
                $goods_arr['products'][$k]['final_price'] = $v[0]['goods_price'];
                $goods_arr['products'][$k]['count'] = $v['num'];
                $goods_arr['products'][$k]['sku_info'] = $sku_info;
                if ($list_id) {
                    if (!in_array($v[0]['goods_id'], $list_id)) {
                        $goods_id_str .= "," . $v[0]['goods_id'];
                    }
                }
                if ($v[0]['goods_price'] > $single_quota) {
                    $out_goods_arr[$v[0]['goods_id']] = $v[0]['goods_price'] - $single_quota;
                    $out_money += $v[0]['goods_price'] - $single_quota;
                }

            }


            //判断订单是超出当月预算或者超出商品选购范围或者单个商品超出预算
            $out_goods_arr_serialize = serialize($out_goods_arr);

            $goods_id_str_serialize = serialize(mb_substr($goods_id_str, 1, strlen($goods_id_str)));
            $money = $money + $post['express_fee'];
            $data['reason'] = "";
            if ($money > $total_quota_left && $total_quota != 0) {
                $data['reason'] .= ',超出当月预算' . ($money - $total_quota_left) . '元';
            }

            if (unserialize($goods_id_str_serialize)) {
                $data['reason'] .= ',超出商品选购范围';
            }
            if (unserialize($out_goods_arr_serialize) && $single_quota != 0) {
                $data['reason'] .= ',单个商品超出预算';
            }

            $data['reason'] = mb_substr($data['reason'], 1, strlen($data['reason']));
            if (($money > $total_quota_left && $total_quota != 0) || unserialize($goods_id_str_serialize) || (unserialize($out_goods_arr_serialize) && $single_quota != 0)) {
                $data['money'] = $money;
                $data['address_id'] = $post['address_id'];
                $data['customer_id'] = $customer_id;
                // if (isset($post['bm'])) {
                //     $data['cost_center_id'] = $post['bm'];
                // } else {
                //     $data['cost_center_id'] = $this->customer_model->query_customer_info($customer_id)['cost_center_id'];
                // }
                $data['invoice_id'] = $post['invoice_id'];
                $data['express_fee'] = $post['express_fee'];
                $data['detail'] = json_encode($goods_arr);
                $data['remark'] = $post['message'];
                $data['content'] = $post['content'];
                if ($identity == 3) {
                    $parent_info = $this->customer_model->get_parent_info($customer_id);
                    if($parent_info['identity'] == 1){
                       $data['status'] = 4;
                    }else{
                        $data['status'] = 2;
                    }
                    
                } elseif ($identity == 2) {
                    $data['status'] = 4;
                }
                $data['created_at'] = date("Y-m-d H:i:s", time());
                $data['update_at'] = date("Y-m-d H:i:s", time());
                $res = $this->db->insert('app_temp', $data);
                $temp_id = $this->db->insert_id();
                if ($res) {

                    if ($post['submit_type'] == 1) {
                        foreach ($cart_id as $key => $value) {
                            $where = array(
                                'id' => $value
                            );
                            $this->db->where($where)->delete('app_cart');
                        }
                    }

                    $where = array(
                        'customer_id' => $customer_id
                    );
                    $this->db->where($where)->delete('app_temp_order');

                    $reason = "";
                    if ($money > $total_quota_left && $total_quota != 0) {
                        $temp1['temp_id'] = $temp_id;
                        $temp1['exceed_budget'] = $money - $total_quota_left;
                        $this->db->insert('app_temp_month_budget', $temp1);
                        $reason .= "订单超出预算,";
                    }
                    if (unserialize($goods_id_str_serialize)) {
                        $temp2['temp_id'] = $temp_id;
                        $temp2['out_list_product_ids'] = $goods_id_str_serialize;
                        $this->db->insert('app_temp_out_list', $temp2);
                        $reason .= "商品超出选购范围,";
                    }
                    if (unserialize($out_goods_arr_serialize) && $single_quota != 0) {
                        $temp3['temp_id'] = $temp_id;
                        $temp3['out_single_product_ids'] = $out_goods_arr_serialize;
                        $temp3['out_money'] = $out_money;
                        $this->db->insert('app_temp_single_budget', $temp3);
                        $reason .= "单品超出预算,";
                    }
                    if ($identity == 3) {
                        $parent_info = $this->customer_model->get_parent_info($customer_id);
                        if($parent_info['status'] == 0){
                           $parent = $this->customer_model->get_parent_info($parent_info['id']);
                        }else{
                            $parent = $this->customer_model->get_parent_info($customer_id);
                        }
                        
                    }else{
                        $parent = $this->customer_model->get_parent_info($customer_id);
                    }
                    $email = $parent['email'];
                    $id = $parent['id'];
                    $content = '【文具1号】尊敬的客户，你的user/manager用户订单，' . $reason . '需要您及时审批，详情请登录（www.wjyh.com）。';
                    $res = $this->api_model->send_email_public($email, '审批订单', $content);
                    echo '<script>location.href="' . $this->config->item('base_url') . '/order/approve_order' . '";</script>';
                }

            } else {
                if ($post['submit_type'] == 1) {
                    $cart_id = [];
                    foreach ($goods as $k => $v) {
                        //企业购物车id
                        $cart_id[$k] = $v['id'];
                    }
                }   
                $url = $this->config->item('shop_url') . 'companymanagerapi/companyCreateOrder/';

                $data_arr['buyerId'] = $shop_user_id;
                $data_arr['addressId'] = $post['regionId'];
                $data_arr['invoice_id'] = $post['invoice_id'] ? $post['invoice_id'] : "";
                $data_arr['type'] = $post['type'] ? $post['type'] : "";
                $data_arr['invoice_cont'] = $post['invoice_cont'] ? $post['invoice_cont'] : "";

                $data_arr['time'] = time();
                $data_arr['key'] = md5($this->config->item("token_const_wjyh") . $data_arr['time']);
                $rs = curl_request($url, $data_arr);
                $result = json_decode($rs, true);
                if ($result['code'] == 200) {
                    if ($post['submit_type'] == 1) {
                        foreach ($cart_id as $key => $value) {
                            $where = array(
                                'id' => $value
                            );
                            $this->db->where($where)->delete('app_cart');
                        }
                    }

                    $where = array(
                        'customer_id' => $customer_id
                    );
                    $this->db->where($where)->delete('app_temp_order');
                    $re = $this->db->query('select query_admin_id(' . $customer_id . ') as admin_id')->row_array();

                    $where = array('customer_id' => $customer_id,'shop_order_id'=>$result['data']['order_id'][0]);
                    sleep(2);
                    $order_result = $this->db->where($where)->update('app_order', array('payment_url' => $result['data']['url'], 'admin_customer_id' => $re['admin_id'],'cost_center_id'=>$data['cost_center_id']));
                    echo '<script>location.href="' . $result['data']['url'] . '";</script>';
                } else {
                    $this->session->set_flashdata('msg', '提交订单处理失败');
                    echo '<script>location.href="' . base_url('cart') . '";</script>';
                }
            }
        } else {
            if ($post['submit_type'] == 1) {
                $cart_id = [];
                foreach ($goods as $k => $v) {
                    //企业购物车id
                    $cart_id[$k] = $v['id'];
                }
            }
            $url = $this->config->item('shop_url') . 'companymanagerapi/companyCreateOrder/';

            $data_arr['buyerId'] = $shop_user_id;
            $data_arr['addressId'] = $post['regionId'];
            $data_arr['invoice_id'] = $post['invoice_id'] ? $post['invoice_id'] : "";
            $data_arr['type'] = $post['type'] ? $post['type'] : "";
            $data_arr['invoice_cont'] = $post['invoice_cont'] ? $post['invoice_cont'] : "";
            $data_arr['time'] = time();
            $data_arr['key'] = md5($this->config->item("token_const_wjyh") . $data_arr['time']);
            $rs = curl_request($url, $data_arr);
            $result = json_decode($rs, true);
            if ($result['code'] == 200) {
                if ($post['submit_type'] == 1) {
                    foreach ($cart_id as $key => $value) {
                        $where = array(
                            'id' => $value
                        );
                        $this->db->where($where)->delete('app_cart');
                    }
                }

                $where = array(
                    'customer_id' => $customer_id
                );
                $this->db->where($where)->delete('app_temp_order');
                $re = $this->db->query('select query_admin_id(' . $customer_id . ') as admin_id')->row_array();
                $where = array('customer_id' => $customer_id,'shop_order_id'=>$result['data']['order_id'][0]);
                sleep(2);
                $this->db->where($where)->update('app_order', array('payment_url' => $result['data']['url'], 'admin_customer_id' => $re['admin_id'],'cost_center_id'=>$data['cost_center_id']));
                echo '<script>location.href="' . $result['data']['url'] . '";</script>';
            } else {
                $this->session->set_flashdata('msg', '提交订单处理失败');
                echo '<script>location.href="' . base_url('cart') . '";</script>';
            }

        }
    }

    //通过类型查询用户默认发票信息
    public function user_invoice_type_default()
    {
        $post = $this->input->post();
        $invoice = $this->user_model->query_user_invoice_type_default($post['uid'], $post['type']);
        if ($invoice) {
            send_json(array('code' => 0, 'data' => $invoice, 'msg' => ''));
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => ''));
        }
    }

    /*
     * 添加/修改发票信息
     * $post['id'] 为发票id ，$post['type'] 发票类型 $post['uid'] 发票用户customer_id
      */
    public function add_mdy_invoice()
    {
        $customer_id = $this->session->customer_id;
        $shop_user_id = $this->user_model->customer_id_to_shop_user_id($customer_id);
        $post = $this->input->post();
        
        if ($post) {
            //普通发票的增加或者修改和同步
            if ($post['type'] == 4) {
                $data['customer_id'] = isset($post['uid']) ? $post['uid'] : "";
                $data['invoice_type'] = isset($post['type']) ? $post['type'] : "";
                $data['invoice_company_name'] = isset($post['title']) ? $post['title'] : "";
                $data['invoice_content'] = isset($post['cont']) ? $post['cont'] : 1;
                $data['invoice_code'] = isset($post['qycode']) ? $post['qycode'] : "";
                $data['is_default'] = isset($post['is_default']) ? $post['is_default'] : 1;
                if ($data['is_default'] == 1) {
                    $where = array('customer_id' => $post['uid']);
                    $this->db->where($where)->update('app_invoice', array('is_default' => 0));
                }
                if ($post['id'] == 0) {
                    
                    $res = $this->db->insert('app_invoice', $data);
                    $invoice_id = $this->db->insert_id();
                    if ($res) {
                        $data['shop_user_id'] = $shop_user_id;
                        $shop_id = $this->member_model->company_user_invoice($data);
                        $where = array('id' => $invoice_id);
                        $this->db->where($where)->update('app_invoice', array('shop_id' => $shop_id['data']));
                        send_json(array('code' => 0, 'data' => $shop_id['data'], 'msg' => '添加成功'));
                    } else {
                        send_json(array('code' => -1, 'data' => "", 'msg' => '添加失败'));
                    }
                } else {
                    $where = array('shop_id' => $post['id']);
                    $res = $this->db->where($where)->update('app_invoice', $data);
                    if ($res) {
                        $row = $this->db->select('shop_id')->where($where)->from('app_invoice')->get()->row_array();
                        $data['shop_id'] = $row['shop_id'];
                        $data['shop_user_id'] = $shop_user_id;
                        $this->member_model->company_user_invoice($data);
                        send_json(array('code' => 0, 'data' => $row['shop_id'], 'msg' => '修改成功'));
                    } else {
                        send_json(array('code' => -1, 'data' => "", 'msg' => '修改失败'));
                    }
                }
                //增值发票的增加或者修改和同步
            } elseif ($post['type'] == 2) {
                $data['customer_id'] = isset($post['uid']) ? $post['uid'] : "";
                $data['invoice_type'] = isset($post['type']) ? $post['type'] : "";
                $data['invoice_company_name'] = isset($post['company']) ? $post['company'] : "";
                $data['invoice_address'] = isset($post['address']) ? $post['address'] : "";
                $data['invoice_tel'] = isset($post['tel']) ? $post['tel'] : "";
                $data['invoice_bank'] = isset($post['bank']) ? $post['bank'] : "";
                $data['invoice_account'] = isset($post['card']) ? $post['card'] : "";
                $data['invoice_code'] = isset($post['texpayer']) ? $post['texpayer'] : "";
                $data['is_default'] = isset($post['is_default']) ? $post['is_default'] : 1;
                if ($data['is_default'] == 1) {
                    $where = array('customer_id' => $post['uid']);
                    $this->db->where($where)->update('app_invoice', array('is_default' => 0));
                }
                if ($post['id'] == 0) {
                    $res = $this->db->insert('app_invoice', $data);
                    $invoice_id = $this->db->insert_id();
                    if ($res) {
                        $data['shop_user_id'] = $shop_user_id;
                        $shop_id = $this->member_model->company_user_invoice($data);
                        $where = array('id' => $invoice_id);
                        $this->db->where($where)->update('app_invoice', array('shop_id' => $shop_id['data']));
                        send_json(array('code' => 0, 'data' => $shop_id['data'], 'msg' => '添加成功'));
                    } else {
                        send_json(array('code' => -1, 'data' => "", 'msg' => '添加失败'));
                    }
                } else {
                    $where = array('shop_id' => $post['id']);
                    $res = $this->db->where($where)->update('app_invoice', $data);
                    if ($res) {
                        $row = $this->db->select('shop_id')->where($where)->from('app_invoice')->get()->row_array();
                        $data['shop_id'] = $row['shop_id'];
                        $data['shop_user_id'] = $shop_user_id;
                        $this->member_model->company_user_invoice($data);
                        send_json(array('code' => 0, 'data' => $row['shop_id'], 'msg' => '修改成功'));
                    } else {
                        send_json(array('code' => -1, 'data' => "", 'msg' => '修改失败'));
                    }
                }

            } else {
                send_json(array('code' => 0, 'data' => "", 'msg' => '暂不需要'));
            }
        }


    }

    //获取用户地址信息
    public function get_address()
    {
        $post = $this->input->post();
        if ($post) {
            $where = array('id' => $post['id']);
            $address = $this->db->where($where)->from('app_address')->get()->row_array();

            if ($address) {
                send_json(array('code' => 0, 'data' => $address, 'msg' => ""));
            } else {
                send_json(array('code' => -1, 'data' => "", 'msg' => "地址不存在"));
            }
        }
    }

    // 新增订单信息
    // public function add_order_info()
    // {
    //     $post = $this->input->post();
    //     log_message("error", json_encode($post));
    //     if (check_param($post, ['order_bn', 'shop_customer_id', 'money', 'express_fee', 'status', 'order_at', 'order_info'])) {
    //         $res = $this->order_model->add_order_info($post);
    //         if ($res) {
    //             send_json(array('code' => 0, 'data' => '', 'msg' => "同步成功"));
    //         } else {
    //             send_json(array('code' => -1, 'data' => '', 'msg' => "同步失败"));
    //         }
    //     } else {
    //         send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
    //     }

    // }

    // 订单修改状态
    // public function update_order_status()
    // {
    //     $post = $this->input->post();
    //     log_message("error", json_encode($post));
    //     if (check_param($post, ['order_bn', 'shop_customer_id', 'money', 'status', 'order_info'])) {
    //         $res = $this->order_model->update_order_info($post);
    //         if ($res) {
    //             send_json(array('code' => 0, 'data' => '', 'msg' => "同步成功"));
    //         } else {
    //             send_json(array('code' => -1, 'data' => '', 'msg' => "同步失败"));
    //         }
    //     } else {
    //         send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
    //     }

    // }

    // 读取多地址Excel中的内容，生成订单
    // public function upload_multi_address_excel()
    // {
    //     $user_id = $this->session->customer_id;
    //     if ($user_id) {
    //         $config['upload_path'] = './uploads/';
    //         $config['allowed_types'] = 'xls|xlsx|xltx';
    //         $config['max_size'] = $this->config->item("max_excel_size");;
    //         $config['file_name'] = 'excel_file' . $user_id;
    //         $config['overwrite'] = TRUE;

    //         $this->load->library('upload', $config);

    //         if (!$this->upload->do_upload('excel_file')) {
    //             $error = array('error' => $this->upload->display_errors());

    //             $this->load->view('upload_form', $error);
    //         } else {
    //             $data = array('upload_data' => $this->upload->data());

    //             $this->load->view('upload_success', $data);
    //         }
    //     } else {

    //     }

    // }
}